/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package users.tag;

import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.tagext.TagSupport;
import tracker.Torrents;
import tracker.TrackerHelper;

/**
 *
 * @author Hiro
 */
public class UploadTagHandler extends TagSupport {

    private String torrentName;
    private String torrentDescription;
    private String torrentTime;

    @Override
    public int doStartTag() throws JspException {
        return super.doStartTag();
    }

    @Override
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();
        Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
        Matcher m = p.matcher(torrentName);
        if (m.matches()) {
            try {
                TrackerHelper helper = new TrackerHelper();
                Collection<Torrents> list = helper.getTorrentByName(torrentName);
                Iterator<Torrents> it = list.iterator();

                while (it.hasNext()) {
                    Torrents tor = it.next();
                    if (tor.getTorrentName().equals(torrentName)) {
                        out.println("<h2 style=\"width:800px; margin:0 auto;\">Failed! Torrent existed! Please rename or upload another!</h2>");
                        return 0;
                    }
                }
                helper.addTorrent(torrentName, torrentDescription, torrentTime);
                out.println("<h2 style=\"width:800px; margin:0 auto;\">Upload Successfully!</h2>");
            } catch (Exception e) {
                System.out.println("<h2 style=\"width:800px; margin:0 auto;\">Failed! Error in upload torrent!: " + e.getMessage()+"</h2>");
            }
        }
        return EVAL_PAGE;
    }

    public void setTorrentName(String torrentName) {
        this.torrentName = torrentName;
    }

    public void setTorrentDescription(String torrentDescription) {
        this.torrentDescription = torrentDescription;
    }

    public void setTorrentTime(String torrentTime) {
        this.torrentTime = torrentTime;
    }

}
